<?php

namespace Frieza\Modules\Totem\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\model\AdmMsgSendDetails;
use Doraemon\model\Member;
use Doraemon\service\AdmMsgSend as sAdmMsgSend;
use Doraemon\service\BadgeService;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Totem\Totems as mTotems;
use Doraemon\service\Totem\TotemService;
use Doraemon\model\Totem\TotemTypes as mTotemTypes;
use Illuminate\Support\MessageBag;
use Frieza\Modules\Totem\Actions\UpdateTotem;
use Frieza\Modules\Totem\Actions\SoldOutTotem;
use Frieza\Modules\Totem\Actions\RackTotem;


class IndexController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $limit = [($page - 1) * $pageSize, $pageSize];
        //处理无筛选参数的情况
        $all_totem_info = mTotems::getAllBadges($limit);
        if ($request_data){
            //处理有筛选参数的情况
            if ($request_data['_sort']){
                //处理排序
                $where['ORDER'] = [$request_data['_sort']['column'] => strtoupper($request_data['_sort']['type'])];
                $where['LIMIT'] = $limit;
                $all_totem_info = mTotems::selectByWhere($where);
            }
        }
        $all_totem_info = TotemService::formatTotemInfo($all_totem_info);
        $total = mTotems::count('*');
        $gridModel = new GridDataModel($all_totem_info, $total, [
            'perPage' => $pageSize,
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增徽章', '', url('/admin/totem/create')));
                });
                $grid->setActionClass(DropdownActions::class);
                $grid->perPages([10, 20, 30, 40, 50, 100, 500, 1000, 2000, 5000]);
                $grid->column('id', 'Id')->sortable();
                $grid->column('totem_name', '徽章名称');
                $grid->column('group_name', '徽章分组');
                //$grid->column('totem_desc', '徽章说明')->width(100);
                $grid->column('is_wear', '是否可佩戴');
                $grid->column('is_scroll', '是否可滚动');
                //$grid->column('button_word', '按钮文案');
                //$grid->column('button_link', '按钮链接')->width(100);

                $grid->column('totem_img', '徽章亮图')->display(function(){
                    return '<img src = "'.$this->totem_img.'" height = 60px />';
                });
                $grid->column('totem_dark_img', '徽章灰图')->display(function(){
                    return '<img src = "'.$this->totem_dark_img.'" height = 60px />';
                });
                $grid->column('totem_small_img', '徽章小icon图')->display(function(){
                    return '<img src = "'.$this->totem_small_img.'" height = 48px />';
                });
                $grid->column('totem_big_img', '徽章大icon图')->display(function(){
                    return '<img src = "'.$this->totem_big_img.'" height = 48px />';
                });
                $grid->column('totem_scroll_img', '徽章滚动图')->display(function(){
                    return '<img src = "'.$this->totem_scroll_img.'" height = 60px />';
                });
                $grid->column('start_time', '徽章上线时间');
                $grid->column('end_time', '徽章下线时间');
                $grid->column('totem_status', '徽章状态');
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '编辑时间');
                $grid->column("admin_id", '操作人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->admin_id)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $id = $actions->row->id;
                    //获取徽章信息
                    $totem_info = mTotems::get('*',['id' => $id]);
                    if ($totem_info['totem_status'] == mTotems::STATUS_DELETE){
                        $actions->add(new RackTotem);
                    }else{
                        $actions->add(new UpdateTotem);
                        $actions->add(new SoldOutTotem);
                    }

                });
            });

        return $content
            ->header('徽章列表')
            ->description('所有徽章信息')
            ->row($gridList);
    }


    /**
     * 新增徽章视图
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function create(Request $request, Content $content)
    {
        $header = '新增徽章';
        $row = [];
        $form = new Form($row);
        $tab = new Tab();
        $tab->add($header, $form);
        //徽章所有的分类
        $totem_all_type = mTotemTypes::GROUP_DESC;
        //获取徽章的所有分组
        $group_info = mTotemTypes::getAllType();
        $group_arr = [];
        foreach ($group_info as $value){
            $group_arr[$value['id']] = $value['type_name'];
        }
        $form->text('totem_name', '徽章名称')->required();
        $form->text('totem_desc', '徽章说明')->required();
        $form->select('totem_type','徽章所属分类')->options($totem_all_type)->load('group', route('totem.group'))->required();
        $form->select('group','徽章所属分组');
        $form->number('unlock_num','徽章解锁数量')->required()->default(0);
        $form->radio('is_wear','是否可佩戴')->options(['0' => '不可佩戴', '1'=> '可佩戴'])->default('1');
        $form->radio('is_scroll','是否可滚动')->options(['0' => '不可滚动', '1'=> '可滚动'])->default('1');
        $form->text('msg_code', '徽章下行消息code码');
        $form->text('button_word', '按钮文案');
        $form->divider();
        $form->multiLinkSelect('button_link', '按钮链接');
        $form->divider();
        $form->imgUpload('totem_img', '徽章亮图')->help('单图，必须需要上传');
        $form->imgUpload('totem_dark_img', '徽章灰图')->help('单图，必须需要上传');
        $form->imgUpload('totem_small_img', '徽章小icon图 安卓')->help('单图，必须需要上传');
        $form->imgUpload('totem_big_img', '徽章大icon图 IOS')->help('单图，必须需要上传');
        $form->imgUpload('totem_scroll_img', '徽章滚动图')->help('单图，必须需要上传');
        $form->datetime('start_time','徽章上线时间')->format('YYYY-MM-DD HH:mm:ss')->default('');
        $form->datetime('end_time','徽章下线时间')->format('YYYY-MM-DD HH:mm:ss')->default('');
        $form->action(url('admin/totem/save'));
        return $content
            ->header('新增徽章')
            ->description('添加新徽章')
            ->breadcrumb(['text' => '添加新徽章'])
            ->body($tab);
    }

    /**
     * 执行添加徽章
     * @param Request $request
     * @param Content $content
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->input();
            unset($params['_token']);
            //dd($params);
            TotemService::saveTotem($params);
            return redirect(url('/admin/totem/index'))->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }


    /**
     * 编辑徽章视图
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function edit(Request $request, Content $content,$id)
    {
        $header = '编辑徽章信息';
        $row = [];
        //徽章所有的分类
        $totem_all_type = mTotemTypes::GROUP_DESC;
        //获取徽章信息
        $row = mTotems::getAllInfoById($id);
        $type_info = mTotemTypes::getInfoById($row['type_id']);
        $row['totem_type'] = $type_info['group_id'];
        $row['group'] = $row['type_id'];
        unset($row['type_id']);
        $row['button_link'] = json_decode($row['button_link'],true);
        $row['start_time'] = date('Y-m-d H:i:s',$row['start_time']);
        $row['end_time'] = date('Y-m-d H:i:s',$row['end_time']);
        $form = new Form($row);
        $tab = new Tab();
        $tab->add($header, $form);
        //获取徽章的所有分组
        $group_info = mTotemTypes::getAllType();
        $group_arr = [];
        foreach ($group_info as $value){
            $group_arr[$value['id']] = $value['type_name'];
        }
        $group = $row['totem_type'] > 0 ? mTotemTypes::getTypeByGroupId($row['totem_type']) : [];
        $group_info = [];
        foreach ($group as $key => $value){
            $group_info[$value['id']] = $value['type_name'];
        }
        //dd($group_info);
        if ($id) {
            $form->hidden('id');
        }
        $form->text('totem_name', '徽章名称')->required();
        $form->text('totem_desc', '徽章说明')->required();
        $form->select('totem_type','徽章所属分类')->options($totem_all_type)->load('group', route('totem.group'))->required();
        $form->select('group','徽章所属分组')->options($group_info);
        $form->number('unlock_num','徽章解锁数量')->required();
        $form->radio('is_wear','是否可佩戴')->options(['0' => '不可佩戴', '1'=> '可佩戴']);
        $form->radio('is_scroll','是否可滚动')->options(['0' => '不可滚动', '1'=> '可滚动']);
        $form->text('msg_code', '徽章下行消息code码');
        $form->text('button_word', '按钮文案');
        $form->divider();
        $form->multiLinkSelect('button_link', '按钮链接');
        $form->divider();
        $form->imgUpload('totem_img', '徽章亮图')->help('单图，必须需要上传');
        $form->imgUpload('totem_dark_img', '徽章灰图')->help('单图，必须需要上传');
        $form->imgUpload('totem_small_img', '徽章小icon图 安卓')->help('单图，必须需要上传');
        $form->imgUpload('totem_big_img', '徽章大icon图 IOS')->help('单图，必须需要上传');
        $form->imgUpload('totem_scroll_img', '徽章滚动图')->help('单图，必须需要上传');
        $form->datetime('start_time','徽章上线时间')->format('YYYY-MM-DD HH:mm:ss')->default($row['start_time']);
        $form->datetime('end_time','徽章下线时间')->format('YYYY-MM-DD HH:mm:ss')->default($row['end_time']);
        $form->action(url('admin/totem/save'));
        return $content
            ->header('编辑徽章')
            ->description('编辑徽章')
            ->breadcrumb(['text' => '编辑徽章信息'])
            ->body($tab);
    }

    public function group(Request $request)
    {
        $type_id = $request->input('q', 1);
        //获取type_id下的所有group
        $group_info = mTotemTypes::getTypeByGroupId($type_id);
        //dd($group_info);
        $group_arr = [];
        foreach ($group_info as $key => $value){
            $group_arr[$key]['id'] = $value['id'];
            $group_arr[$key]['text'] = $value['type_name'];
        }
        return response()->json($group_arr);
    }
}
